package com.jasmine.bjstkserver.server.article.log.draftlog;
import com.jasmine.core.util.SnowFlake;
import com.jasmine.core.util.SpringContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 文章修改日志切面
 *
 * @author jasmineXz
 */
@Aspect
@Component
public class DraftLogAspect {
    private static final Logger log = LoggerFactory.getLogger(DraftLogAspect.class);

    @Around("@annotation(DraftLog)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        DraftLogEntity log = transformation(args);
        args[0] = log;
        Object obj = point.proceed(args);
        SpringContextHolder.publishEvent(new DraftLogEvent(log));
        return obj;
    }

    private DraftLogEntity transformation (Object[] args) {
        DraftLogEntity log = (DraftLogEntity)args[0];
        log.setVersion(String.valueOf(SnowFlake.nextId()));
        Optional.ofNullable(log.getArticleId()).orElseThrow(() -> new IllegalArgumentException("未收到文章ID"));
        log.setCreTime(LocalDateTime.now());
        return log;
    }
}
